package world.hezi.handlers;

import kotlin.coroutines.CoroutineContext;
import net.mamoe.mirai.contact.Contact;
import net.mamoe.mirai.event.EventHandler;
import net.mamoe.mirai.event.ListeningStatus;
import net.mamoe.mirai.event.SimpleListenerHost;
import net.mamoe.mirai.event.events.MessageEvent;
import net.mamoe.mirai.message.data.*;
import net.mamoe.mirai.utils.ExternalResource;
import org.apache.ibatis.annotations.Insert;
import org.jetbrains.annotations.NotNull;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import world.hezi.bot.BeatsaverBot;
import world.hezi.entity.PicInfo;
import world.hezi.entity.PicTag;
import world.hezi.entity.UserXp;
import world.hezi.http.GetPicturesCache;
import world.hezi.mapper.PicInfoMapper;
import world.hezi.mapper.PicTagMapper;
import world.hezi.mapper.UserXpMapper;
import world.hezi.pools.JedisPools;
import world.hezi.utils.PicturesUtil;

import java.io.File;
import java.util.*;

public class HPicturesHandlers extends SimpleListenerHost {
    Set<Long> groupNumbers = BeatsaverBot.H_PICTURES;
    private final PicInfoMapper picInfoMapper;
    private Jedis jedis;
    private final PicTagMapper picTagMapper;
    private final UserXpMapper userXpMapper;

    public HPicturesHandlers(PicInfoMapper picInfoMapper, PicTagMapper picTagMapper, UserXpMapper userXpMapper, Jedis jedis) {
        this.picInfoMapper = picInfoMapper;
        this.jedis = jedis;
        this.picTagMapper = picTagMapper;
        this.userXpMapper = userXpMapper;
    }

    @Override
    public void handleException(@NotNull CoroutineContext context, @NotNull Throwable exception){
        // 处理事件处理时抛出的异常
    }
    @NotNull
    @EventHandler
    public ListeningStatus onMessage(@NotNull MessageEvent event) {
        try {
            if (groupNumbers.contains(event.getSource().getSubject().getId())){
                Message metaMessage = event.getMessage();
                Contact contact = event.getSubject();
                int re = PicturesUtil.checkAndSave(picInfoMapper,jedis,event.getSender().getId(),metaMessage);
                if (re>=0){
                    MessageChain chain = new MessageChainBuilder()
                                .append(new At(event.getSender().getId()))
                                .append(" 上传完毕，本次上传了")
                                .append(String.valueOf(re))
                                .append("张")
                                .build();
                        contact.sendMessage(chain);
                        return ListeningStatus.LISTENING;
                }else if (re==-1)
                    return ListeningStatus.LISTENING;
                String message = metaMessage.contentToString();
                int type = PicturesUtil.getType(message);
                Long sender = event.getSender().getId();
                switch (type){
                    //单张色图
                    case 0:{
                        List<Image> randomPicture = PicturesUtil.getRandomPicture(sender, contact, 1, userXpMapper, jedis);
                        if (randomPicture.size()==0){
                            contact.sendMessage("你没有xp或者你的xp下没有色图，快用“添加xp:tag名”来添加一个xp吧");
                        }else {
                            contact.sendMessage(randomPicture.get(0));
                        }
                        break;
                    }
                    //上传色图
                    case 10:{
                        String[] split = message.split("[:：]");
                        if (split.length!=2)
                            return ListeningStatus.LISTENING;
                        String tag = split[1];
                        List<PicTag> picTags = picTagMapper.selectAll();
                        boolean flag = false;
                        for (PicTag picTag : picTags) {
                            if (picTag.getTag().equals(tag)){
                                flag = true;
                                break;
                            }
                        }
                        if (!flag){
                            MessageChain chain = new MessageChainBuilder()
                                    .append(new At(event.getSender().getId()))
                                    .append(" 图片tag不存在，请使用 新增图片tag:tag名 来新增一个tag，或使用 图片tag 来查看当前已有tag")
                                    .build();
                            contact.sendMessage(chain);
                            return ListeningStatus.LISTENING;
                        }
                        jedis.set("add:"+sender, tag+":0");
                        contact.sendMessage("请连续发送图片，发送任意不含图片的消息视为上传结束。");
                        break;
                    }
                    //添加xp
                    case 20:{
                        String[] split = message.split("[:：]");
                        if (split.length!=2)
                            return ListeningStatus.LISTENING;
                        Integer tagId;
                        try {
                            if (split[1].equals("这是宅氏群涩图其他群的人别看总之就是不准涩涩知道吗")){
                                if (event.getSource().getSubject().getId()!=157793559){
                                    MessageChain chain = new MessageChainBuilder()
                                            .append(new At(event.getSender().getId()))
                                            .append(" 无权限")
                                            .build();
                                    contact.sendMessage(chain);
                                    break;
                                }
                            }
                            tagId = picTagMapper.selectTagId(split[1]);
                            if (tagId==null){
                                MessageChain chain = new MessageChainBuilder()
                                        .append(new At(event.getSender().getId()))
                                        .append(" tag不存在，请使用 添加tag:tag名 来新增一个tag，或使用 图片tag 来查看当前已有tag")
                                        .build();
                                contact.sendMessage(chain);
                                break;
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            MessageChain chain = new MessageChainBuilder()
                                    .append(new At(event.getSender().getId()))
                                    .append(" tag不存在，请使用 添加tag:tag名 来新增一个tag，或使用 图片tag 来查看当前已有tag")
                                    .build();
                            contact.sendMessage(chain);
                            break;
                        }
                        UserXp userXp = new UserXp();
                        userXp.setUserId(sender);
                        userXp.setTagId(tagId);
                        try {
                            List<String> userXp1 = userXpMapper.getUserXp(sender);
                            if (userXp1.contains(split[1])){
                                MessageChain chain = new MessageChainBuilder()
                                        .append(new At(event.getSender().getId()))
                                        .append(" xp已存在！")
                                        .build();
                                contact.sendMessage(chain);
                                break;
                            }
                            userXpMapper.insert(userXp);
                            MessageChain chain = new MessageChainBuilder()
                                    .append(new At(event.getSender().getId()))
                                    .append(" 添加成功")
                                    .build();
                            contact.sendMessage(chain);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                    }
                    //删除xp
                    case 21:{
                        String[] split = message.split("[:：]");
                        if (split.length!=2)
                            return ListeningStatus.LISTENING;
                        try {
                            userXpMapper.delUserXp(sender,split[1]);
                            MessageChain chain = new MessageChainBuilder()
                                    .append(new At(event.getSender().getId()))
                                    .append("删除成功")
                                    .build();
                            contact.sendMessage(chain);
                        } catch (Exception e) {
                            MessageChain chain = new MessageChainBuilder()
                                    .append(new At(event.getSender().getId()))
                                    .append("删空气？")
                                    .build();
                            contact.sendMessage(chain);
                            e.printStackTrace();
                        }
                        break;
                    }
                    //我的xp
                    case 22:{
                        List<String> userXp = null;
                        try {
                            userXp = userXpMapper.getUserXp(sender);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        MessageChainBuilder messages = new MessageChainBuilder();
                        messages.append(new At(event.getSender().getId()));
                        if (userXp.size()==0){
                            messages.append(" 没有xp");
                        }else {
                            messages.append(" 你的xp列表：").append("\r\n");
                            for (String s : userXp) {
                                messages.append(s).append("\r\n");
                            }
                            messages.append("\r\n").append("你真恶心");
                        }
                        contact.sendMessage(messages.build());
                        break;
                    }
                    //新增全局xp
                    case 23:{
                        String[] split = message.split("[:：]");
                        if (split.length!=2)
                            return ListeningStatus.LISTENING;
                        PicTag picTag = new PicTag();
                        picTag.setAddUser(sender);
                        picTag.setTag(split[1]);
                        MessageChainBuilder messages = new MessageChainBuilder();
                        messages.append(new At(event.getSender().getId()));
                        try {
                            picTagMapper.insert(picTag);
                            messages.append(" 添加成功！");
                        } catch (Exception e) {
                            messages.append(" 已经有啦！");
                            e.printStackTrace();
                        }
                        contact.sendMessage(messages.build());
                        break;
                    }
                    //查看全局xp
                    case 24:{
                        List<PicTag> picTags = picTagMapper.selectAll();
                        MessageChainBuilder messages = new MessageChainBuilder();
                        messages.append(new At(event.getSender().getId()));
                        messages.append(" 全局图片tag：\n");
                        for (PicTag picTag : picTags) {
                            messages.append(picTag.getTag()).append("(")
                                    .append(String.valueOf(jedis.scard(picTag.getTag())))
                                    .append("张)\r\n");
                        }
                        contact.sendMessage(messages.build());
                        break;
                    }
                    //批量获取图片
                    case 100:{
                        message = getPureNumber(message);
                        int t = PicturesUtil.getNumber(message);
                        MessageChainBuilder messages = new MessageChainBuilder();
                        messages.append(new At(event.getSender().getId()));
                        if (t>10){
                            contact.sendMessage(messages.append("太多了发不下的(最多10张)。").build());
                            break;
                        }
                        List<Image> randomPicture;
                        try {
                            randomPicture = PicturesUtil.getRandomPicture(sender, contact, t , userXpMapper, jedis);
                            for (Image image : randomPicture) {
                                contact.sendMessage(image);
                            }
                        } catch (Exception e) {
                            contact.sendMessage(messages.append("没有这么多涩图，添加更多xp吧，使用添加 xp：tag名 来添加一个xp，使用 图片tag 来查看所有tag").build());
                            e.printStackTrace();
                        }
                        break;
                    }
                }
            }
            return ListeningStatus.LISTENING;
        } catch (Exception e) {
            jedis.close();
            jedis = JedisPools.getJedis();
            e.printStackTrace();
        }
        return ListeningStatus.LISTENING;
    }

    @NotNull
    public static String getPureNumber(String message) {
        message = message.replace("零","0");
        message = message.replace("一","1");
        message = message.replace("二","2");
        message = message.replace("两","2");
        message = message.replace("三","3");
        message = message.replace("四","4");
        message = message.replace("五","5");
        message = message.replace("六","6");
        message = message.replace("七","7");
        message = message.replace("八","8");
        message = message.replace("九","9");
        message = message.replace("十","10");
        return message;
    }

}
